<template>
    <div>
        <div class="container">
            <el-main>
                <el-form ref="advertFormRef" :rules="advertFormRules" :model="advertForm" :label-width="formLabelWidth">
                    <el-form-item label="ID" prop="id" v-if="false">
                        <el-input v-model="advertForm.id" />
                    </el-form-item>
                    <el-form-item label="广告位类型" prop="advType">
                        <el-input v-model="advertForm.advType" clearable class="handle-input mr10" v-if="false"/>
                        <el-select v-model="advertForm.advType" class="handle-select mr10" placeholder="请选择">
                            <el-option v-for="item in advTypeOption" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"/>
                        </el-select>
                    </el-form-item>
					<!-- 资讯常规信息 -->
                    <el-form-item label="广告位名称" prop="advName">
                        <el-input v-model="advertForm.advName" clearable class="handle-input mr10" />
                    </el-form-item>
                    <el-form-item label="广告位设定链接" prop="advLink">
                        <el-input v-model="advertForm.advLink" clearable class="handle-input mr10" />
                    </el-form-item>
                    <el-form-item label="是否显示" prop="isStatus">
                        <el-input v-model="advertForm.isStatus" v-if="false"/>
                        <el-switch v-model="advertForm.isStatus" 
                            :active-value= "2001" :inactive-value= "2002"
                            inline-prompt active-text="是" inactive-text="否" />
                    </el-form-item>
                    <el-form-item label="广告位展示位置" prop="advPosition">
                        <el-input v-model="advertForm.advPosition" clearable class="handle-input mr10" v-if="false"/>
                        <el-select v-model="advertForm.advPosition" class="handle-select mr10" placeholder="请选择">
                            <el-option v-for="item in advPositionOption" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="广告位展现方式" prop="advOpenWay">
                        <el-input v-model="advertForm.advOpenWay" clearable class="handle-input mr10" v-if="false"/>
                        <el-select v-model="advertForm.advOpenWay" class="handle-select mr10" placeholder="请选择">
                            <el-option v-for="item in advOpenWayOption" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数据排序" prop="sort">
                        <el-input v-model="advertForm.sort" v-if="false"></el-input>
                        <el-input-number v-model="sortNum" :min="1" :max="100" :step="1" />
                    </el-form-item>
                </el-form>
            </el-main>
			<el-footer>
                <el-button type="primary" @click="func_onSubmit" plain>保存数据</el-button>
                <el-button type="success" @click="func_onReset" plain>重置表单</el-button>
                <el-button @click="func_closeDialog" plain>取 消</el-button>
			</el-footer>
        </div>
    </div>
</template>

<script>
import { onMounted, ref, reactive, toRefs, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { findAdvertInfoById, addAdvert, saveAdvert } from "../../../../api/hairmanager/advert";
import { loadAdvertOpenWayDict, loadAdvertPositionDict, findChildDictionaryListByParentId } from "../../../../api/dict";
import { NO_DATA_SELECT_ERROR, SUCCESS_ADDDATA_DIALOG_MESSAGE, SUCCESS_DELDATA_DIALOG_MESSAGE, SUCCESS_EDITDATA_DIALOG_MESSAGE } from "../../../../api/CommonErrorMessage.js";

export default {
    name: "advertForm",
	props:{
        selectValue: Object,
	},
    emits: ["advertData"],
    setup(props, cex){
		onMounted(() => {
		});
        const router = useRouter();
		const route = useRoute();
        const formLabelWidth = ref("170px");
		/**
         * @name 定义业务表单
         */
        const getInitFormData = () => {
            return {
				id: 0,
                advLink: '',
                advName: '',
                advOpenWay: '',
                advPosition: '',
                advTemplate: '',
                isStatus: 0,
                sort: 0,
                advType: '1910011',
            }
        };
        /**
         * @name 表单初始化
         */
        const resetAdvertForm = () => {
            Object.assign(advertForm, getInitFormData());
            sortNum.value = 1;
        };
		// 新闻资讯表单数据
        const advertForm = reactive(getInitFormData());
        const advertFormRef = ref(null);
        const advertFormRules = {
            advLink: [
                { required: true, message: "请输入广告位链接", trigger: "blur" },
            ],
            advName: [
                { required: true, message: "请输入广告位名称", trigger: "blur" },
            ],
        };
        const sortNum = ref(0);
        const loadDataFlg = ref(false);
        const advPositionOption = ref([]);
        const advOpenWayOption = ref([]);
        const advTypeOption = ref([]);
        // =========================================================================================================
        // 提交
        const func_onSubmit = () => {
            advertForm['sort'] = sortNum;
            // 表单校验
            advertFormRef.value.validate((valid) => {
                if (valid) {
                    if(loadDataFlg.value){
                        saveAdvert(advertForm).then((res) => {
                            if(res.code != 200) {
                                if(res.type == 0) {
                                    ElMessage.warning(res.message);
                                } else {
                                    ElMessage.error(res.message);
                                }
                            } else {
                                ElMessage.success(SUCCESS_EDITDATA_DIALOG_MESSAGE);
                                cex.emit('advertData', {state: 1, data: []});
                            }
                        });
                    } else {
                        addAdvert(advertForm).then((res) => {
                            if(res.code != 200) {
                                if(res.type == 0) {
                                    ElMessage.warning(res.message);
                                } else {
                                    ElMessage.error(res.message);
                                }
                            } else {
                                ElMessage.success(SUCCESS_ADDDATA_DIALOG_MESSAGE);
                                cex.emit('advertData', {state: 1, data: []});
                            }
                        });
                    }
                    resetAdvertForm();
                } else {
                    return false;
                }
            });
        };
        // 重置
        const func_onReset = () => {
            resetAdvertForm();
        };
        const func_closeDialog = () => {
            cex.emit('advertData', {state: 1, data: []});
        };
        const func_onload = () =>{
            advPositionOption.value = [];
            loadAdvertPositionDict().then((res) => {
                res.data.forEach((item) => {
                    let obj = {value : item['value'], label : item['label']}
                    advPositionOption.value.unshift(obj);
                });
            });
            advOpenWayOption.value = [];
            loadAdvertOpenWayDict().then((res) => {
                res.data.forEach((item) => {
                    let obj = {value : item['value'], label : item['label']}
                    advOpenWayOption.value.unshift(obj);
                });
            });
            let query = {parentId: 71};
            findChildDictionaryListByParentId(query).then((res) => {
                res.data.list.forEach((item) => {
                    let obj = {};
                    if(item['dicCode'] === advertForm['advType']){
                        obj = {value : item['dicCode'], label : item['dicName'], disabled: false}
                    } else {
                        obj = {value : item['dicCode'], label : item['dicName'], disabled: true}
                    }
                    advTypeOption.value.unshift(obj);
                });
            });
        }
        func_onload();
        // =========================================================================================
        // 业务数据监听
        watch(() => props.selectValue, (val) => {
			if(val['load']){
                findAdvertInfoById(props.selectValue['id']).then((res) => {
                    Object.keys(advertForm).forEach((item) => {
                        advertForm[item] = res.data[item];
                    })
                    sortNum.value = advertForm['sort'];
                });
			} else {
                resetAdvertForm();
            }
            loadDataFlg.value = val['load'];
        },{deep: true,immediate: true});
        // =========================================================================================================
        return {
			// 系统变量 =========================================================================================
            formLabelWidth, advertForm, advertFormRef, advertFormRules, sortNum, loadDataFlg, advOpenWayOption, advPositionOption, advTypeOption,
            // 数据执行处理 =========================================================================================
			// 主业务调用方法 =========================================================================================
            func_onload, getInitFormData, resetAdvertForm, func_onSubmit, func_onReset, func_closeDialog,
        };
    },
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 300px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
</style>